package com.xyzh05.dao.hibernate;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.xyzh05.dao.GenericDao;
import com.xyzh05.util.HQLHelper;
import com.xyzh05.util.PageBean;
import com.xyzh05.util.PageUtil;

/**
 * This class serves as the Base class for all other DAOs - namely to hold
 * common CRUD methods that they might all use. You should only need to extend
 * this class when your require custom CRUD logic.
 * <p/>
 * <p>To register this class in your Spring context file, use the following XML.
 * <pre>
 *      &lt;bean id="fooDao" class="com.xyzh05.dao.hibernate.GenericDaoHibernate"&gt;
 *          &lt;constructor-arg value="com.xyzh05.model.Foo"/&gt;
 *      &lt;/bean&gt;
 * </pre>
 *
 * @author <a href="mailto:bwnoll@gmail.com">Bryan Noll</a>
 * @param <T> a type variable
 * @param <PK> the primary key for that type
 */
@SuppressWarnings("unchecked")
public class GenericDaoHibernate<T, PK extends Serializable> extends HibernateDaoSupport implements GenericDao<T, PK> {
    /**
     * Log variable for all child classes. Uses LogFactory.getLog(getClass()) from Commons Logging
     */
    protected final Log log = LogFactory.getLog(getClass());
    private Class<T> persistentClass;

    /**
     * Constructor that takes in a class to see which type of entity to persist.
     * Use this constructor when subclassing.
     *
     * @param persistentClass the class type you'd like to persist
     */
    public GenericDaoHibernate(final Class<T> persistentClass) {
        this.persistentClass = persistentClass;
    }
    
    @Autowired  
    public void setSessionFactoryOverride(SessionFactory sessionFactory) {  
        super.setSessionFactory(sessionFactory);  
    }  

    /**
     * Constructor that takes in a class and sessionFactory for easy creation of DAO.
     *
     * @param persistentClass the class type you'd like to persist
     * @param sessionFactory  the pre-configured Hibernate SessionFactory
     */
    public GenericDaoHibernate(final Class<T> persistentClass, SessionFactory sessionFactory) {
        this.persistentClass = persistentClass;
    }

    /**
     * {@inheritDoc}
     */
    @SuppressWarnings("unchecked")
    public List<T> getAll() {
        return super.getHibernateTemplate().loadAll(this.persistentClass);
    }

    /**
     * {@inheritDoc}
     */
    @SuppressWarnings("unchecked")
    public List<T> getAllDistinct() {
        Collection result = new LinkedHashSet(getAll());
        return new ArrayList(result);
    }

    /**
     * {@inheritDoc}
     */
    @SuppressWarnings("unchecked")
    public T get(PK id) {
        T entity = (T) super.getHibernateTemplate().get(this.persistentClass, id);

        if (entity == null) {
            log.warn("Uh oh, '" + this.persistentClass + "' object with id '" + id + "' not found...");
            throw new ObjectRetrievalFailureException(this.persistentClass, id);
        }

        return entity;
    }

    /**
     * {@inheritDoc}
     */
    @SuppressWarnings("unchecked")
    public boolean exists(PK id) {
        T entity = (T) super.getHibernateTemplate().get(this.persistentClass, id);    	
        return entity != null;
    }

    /**
     * {@inheritDoc}
     */
    @SuppressWarnings("unchecked")
    public T save(T object) {
        return (T) super.getHibernateTemplate().merge(object);
    }

    /**
     * {@inheritDoc}
     */
    @SuppressWarnings("unchecked")
    public void saveOrUpdate(T object) {
    	super.getHibernateTemplate().saveOrUpdate(object);
    }
    
    /**
     * {@inheritDoc}
     */
    public void remove(PK id) {
        super.getHibernateTemplate().delete(this.get(id));
    }

    /**
     * {@inheritDoc}
     */
    @SuppressWarnings("unchecked")
    public List<T> findByNamedQuery(String queryName, Map<String, Object> queryParams) {
        String[] params = new String[queryParams.size()];
        Object[] values = new Object[queryParams.size()];
        
        int index = 0;
        for (String s : queryParams.keySet()) {
            params[index] = s;
            values[index++] = queryParams.get(s);
        }

        return super.getHibernateTemplate().findByNamedQueryAndNamedParam(queryName, params, values);
    }
    
    public PageBean getPageByHQL(String hql, PageBean pageBean,Object...parameters){
    	return getPageByHQL(HQLHelper.getCountHql(hql), hql, pageBean, parameters);
    }
    
    private PageBean getPageByHQL(String countHql, String hql, PageBean pageBean, Object...parameters){
    	if (pageBean == null)
			pageBean = new PageBean();
		int currentPage = pageBean.getPageNumber();
		int onePageRows = pageBean.getObjectsPerPage(); //每页记录数
		if (onePageRows < 0) {
			return new PageBean();
		}
		int totalRows = findCount(countHql, parameters);
		if (totalRows <= 0) {
			return new PageBean();
		}
		int totalPages = PageUtil.getTotPageNum(onePageRows, totalRows);
		if (currentPage < 0) {
			currentPage = 1;
		} else if (currentPage > totalPages) {
			currentPage = totalPages;
		}
		List reList = findOnePageList(hql, (currentPage - 1) * onePageRows, onePageRows, parameters);
		pageBean.setList(reList);  //当前页面的集合
		pageBean.setTotalPages(totalPages);  //总页数
		pageBean.setPageNumber(currentPage); //当前页面
		pageBean.setFullListSize(totalRows); //总记录数
		pageBean.setStartPageNumber(currentPage == 1 ? 1 : ((currentPage-1)*onePageRows)+1);//当前页开始行
		pageBean.setEndPageNumber(currentPage*onePageRows >= totalRows ? totalRows : currentPage*onePageRows);//当前页结束行
		return pageBean;
    }
    
    /**
     * 得到总条数 example： baseDAO.findCount("selete count(*) form User");
     * @param hql
     * @param parameters
     * @return 不存在时返回为0
     */
    private int findCount(final String hql, final Object...parameters) {
		Integer counts = (Integer) super.getHibernateTemplate().execute(
			new HibernateCallback() {
				public Object doInHibernate(Session session) throws HibernateException {
					Query query = session.createQuery(hql);
					int i = 0;
					for (Object parameter : parameters) {
						query.setParameter(i, parameter);
						i++;
					}
					return findGroupBy(hql) ? query.list().size() : new Integer(query.uniqueResult().toString());
				}
			});
		return counts == null ? 0 : counts;
	}
    
    private boolean findGroupBy(String hql) {
		return hql.toLowerCase().contains("group by");
	}
    
    /**
     * 通用分页方法
     * @param hql  要执行的hql语句    
     * @param firstResult  开始的位置
     * @param maxResults 得到的本次查询的条数
     * @param parameters
     * @return
     */
    public List<? extends Object> findOnePageList(final String hql, final Integer firstResult, final Integer maxResults, final Object...parameters) {
		List list = getHibernateTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException {
				Query query = session.createQuery(hql);
				if (firstResult != null && firstResult > -1) {
					query.setFirstResult(firstResult);
				}
				if (maxResults != null && maxResults > -1) {
					query.setMaxResults(maxResults);
				}
				int i = 0;
				for (Object parameter : parameters) {
					query.setParameter(i, parameter);
					i++;
				}
				return query.list();
			}
		});
		return list;
	}
    
    public List<?> findQuery(String hql ,Object...objects){
    	return super.getHibernateTemplate().find(hql, objects);    	
    }
}
